/**
 * engineering-bill list
 */
let $, form, tableSelect, table;
let shipId = "";
let shipName = "";
let loginU = {};
let keyWork = "{}";
let curr = 1;
layui.use(['form', 'table', 'tableSelect'], function () {
    $ = layui.jquery,
        form = layui.form,
        tableSelect = layui.tableSelect,
        table = layui.table;
    let searchFieldsetStatus=localStorage.getItem("searchFieldsetStatus");
    if(searchFieldsetStatus=='0')
    {
        $(".search-display-btn").attr("show","0");
        $(".search-display-btn").html('<i class="fa fa-angle-down"></i>展开');
        $($('.layui-form')[0]).hide();
    }
    setTableHeight();
    let u = localStorage.getItem("ADMIN_LOGIN");
    if (u == undefined) {
        layer.msg('请登录', {icon: 1, time: 500}, function () {
            window.location = 'logout';
        });
    } else {
        loginU = decryptLocalStorage(u);
        if(loginU.userType=='3' || loginU.userType=='4' || loginU.userType=='5')
        {
            $("#shipName").val(loginU.powerShipNames);
            $("#shipId").val(loginU.powerShipIds);
            //$("#shipName").prop('disabled','disabled');
        }
        if(loginU.orgNames!=undefined && loginU.orgNames!='')
        {
            if(loginU.orgNames!='全部门')
            {
                let orgNameArray=loginU.orgNames.split(",");
                if(orgNameArray.length>0)
                {
                    $('#orgName option').each(function(){
                        $(this).remove();
                    });
                    $('#orgName').append('<option value="" selected="">请选择</option>');
                    for(let k=0;k<orgNameArray.length;k++){
                        $('#orgName').append('<option value="'+orgNameArray[k]+'">'+orgNameArray[k]+'</option>');
                    }
                    form.render('select');
                }
            }
        }
    }
    let keyWordShipId=localStorage.getItem("keyWordShipId");
    if(keyWordShipId!=undefined){shipId=keyWordShipId;$("#shipId").val(shipId);}
    let keyWordShipName=localStorage.getItem("keyWordShipName");
    if(keyWordShipName!=undefined){shipName=keyWordShipName;$("#shipName").val(shipName);}
    loadShip();

    let tableUrl = baseUrl + "admin/v1/product/page?productType=1&token=" + loginU.token;
    table.render({
        elem: '#currentTableId',
        url: tableUrl,loginUserType:loginU.userType,
        where: {
            keyWork: JSON.stringify({shipId: shipId, shipName: shipName})
        },
        toolbar: '#toolbarPanel',
        defaultToolbar: ['filter', 'exports'],
        cols: [[
            // {type: "checkbox", align: "center", width: 50},
            {type: "numbers", title: '序号', width: 60, align: "center"},
            // {field: 'shipNames', width: 150, align: "center", title: '船舶', sort: true},
            {field: 'productName', width: 150, align: "center", title: '商品名称', sort: true},
            {field: 'productType', align: "center", width: 100, title: '商品类型', sort: true,
                templet: function (data) {
                    if (data.productType == '1') {
                        return "流量充值";
                    } else if (data.productType == '2') {
                        return "带宽续费"
                    }
                }
            },
            {field: 'sellFlag', align: "center", width: 100, title: '销售状态', sort: true,
                templet: function (data) {
                    if (data.sellFlag == '1') {
                        return "上架";
                    } else if (data.sellFlag == '2') {
                        return "下架"
                    }
                }
            },
            {field: 'productPrice', align: "center", width: 150, title: '商品价格(元)', sort: true,
                templet: function (data) {
                    return data.productPrice/100+"元";
                }},
            {field: 'productQuantity', align: "center", width: 150, title: '数量', sort: true},
            {field: 'productDescribe', align: "center", minWidth: 350, title: '描述', sort: true},
            {title: '操作',fixed: "right", width: 220, toolbar: '#currentTableBar', align: "center"}


        ]],
        limits: [10, 15, 20, 25, 50, 100, 200, 300, 500],
        limit: 20,
        page: true,
        skin: 'line',parseData: function (res) {
            for (let i in res.data) {
                res.data[i].loginUserType = loginU.userType;
            }
            return res;
        },
        done: function (res, page, count) {
            if (res.code === -1) {
                layer.msg('请登录', {icon: 1, time: 500}, function () {
                    window.location = 'logout';
                });
                return;
            }
            if (page != undefined) {
                curr = page;
            }
            for (var i in res.data) {
                var item = res.data[i];
                // if (item.deviceStatus == 1) {
                //     $("tr[data-index='" + i + "']").attr({"style": "color:green"});//将当前行变成绿色
                // } else {
                //     $("tr[data-index='" + i + "']").attr({"style": "color:red"});//将当前行变成红色
                // }
            }
        }
    });

    // 监听搜索操作

    form.on('submit(data-search-btn)', function (data) {
        let keyWordShipId=data.field.shipId;
        let keyWordShipName=data.field.shipName;
        if(keyWordShipId!=undefined && keyWordShipId!='undefined'){localStorage.setItem("keyWordShipId",keyWordShipId);}
        if(keyWordShipName!=undefined && keyWordShipName!='undefined'){localStorage.setItem("keyWordShipName", keyWordShipName);}

        keyWork = JSON.stringify(data.field);
        setTableHeight();
        //执行搜索重载
        table.reload('currentTableId', {
            page: {
                curr: 1
            }
            , where: {
                keyWork: keyWork
            }
        }, 'data');

        return false;
    });

    table.on('rowDouble(currentTableFilter)', function (obj) {
        let data = obj.data;
        localStorage.setItem("productData", encryptLocalStorage(data, loginU.token));
        var index = layer.open({
            title: '详情',
            type: 2,
            shade: 0.2,
            maxmin: true,
            shadeClose: false,
            area: ['80%', '80%'],
            content: '../page/flow-data/view',
            end: function () { setTableHeight();
                //执行搜索重载
                table.reload('currentTableId', {
                    page: {
                        curr: curr
                    }
                    , where: {
                        keyWork: keyWork
                    }
                }, 'data');
            }

        });
        $(window).on("resize", function () {
            layer.full(index);
        });
        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'import') {
            var index = layer.open({
                title: '导入信息',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '../page/flow-data/import',
                end: function () { setTableHeight();
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: curr
                        }
                        , where: {
                            keyWork: keyWork
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        }
        if (obj.event === 'add') {  // 监听添加操作
            localStorage.removeItem('productData');
            var index = layer.open({
                title: '添加信息',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '../page/flow-data/edit',
                end: function () { setTableHeight();
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: curr
                        }
                        , where: {
                            keyWork: keyWork
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        } else if (obj.event === 'edit') {
            var checkStatus = table.checkStatus('currentTableId')
                , datas = checkStatus.data;
            if (datas.length != 1) {
                layer.msg('请选择一条记录进行编辑，不能多选', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
            data = datas[0];
            localStorage.setItem("productData", encryptLocalStorage(data, loginU.token));
            var index = layer.open({
                title: '编辑信息',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '../page/flow-data/edit',
                end: function () { setTableHeight();
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: curr
                        }
                        , where: {
                            keyWork: keyWork
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;

        } else if (obj.event === 'delete') {  // 监听删除操作
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            let params = {token: loginU.token, ids: ''};
            let ids = '';
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    ids += data[i].productId + ',';
                }
                ids = ids.substring(0, ids.length - 1);
            }
            params.ids = ids;
            layer.confirm("确认删除信息，请谨慎操作？", {
                btn: ["确定", "取消"]
            }, function (index) {
                layer.close(index);
                request.delList('product', params, function (result) {
                    if (result.code == 0) {
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 500
                        }, function () {
                            //执行搜索重载
                            table.reload('currentTableId', {
                                page: {
                                    curr: curr
                                }
                                , where: {
                                    keyWork: keyWork
                                }
                            }, 'data');
                        });
                    } else {
                        layer.msg('保存失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            }, function () {
                layer.close(index);
            });


        }
    });

    //监听表格复选框选择
    table.on('checkbox(currentTableFilter)', function (obj) {
        //console.log(obj)
    });

    table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            localStorage.setItem("productData", encryptLocalStorage(data, loginU.token));
            var index = layer.open({
                title: '编辑信息',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '../page/flow-data/edit',
                end: function () { setTableHeight();
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: curr
                        }
                        , where: {
                            keyWork: keyWork
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;
        } else if (obj.event === 'delete') {
            layer.confirm("确认删除，请谨慎操作？", {
                btn: ["确定", "取消"]
            }, function (index) {
                layer.close(index);
                request.del('product', {token: loginU.token, id: obj.data.productId}, function (result) {
                    if (result.code == 0) {
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 500
                        }, function () {
                            obj.del();
                        });
                    } else {
                        layer.msg('保存失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            }, function () {
                layer.close(index);
            });
        }
    });

    function loadShip() {
        let tableUrl = "/admin/v1/ship/page?token=" + loginU.token;
        tableSelect.render({
            elem: '#shipName',
            checkedKey: 'id',
            searchFlag: true,
            searchKey: 'shipName',
            table: {
                url: tableUrl,loginUserType:loginU.userType,
                cols: [[
                    {type: 'radio'},
                    {field: 'shipId', title: 'ID'},
                    {field: 'shipName', title: '船舶'}
                ]]
            },
            done: function (elem, data) {
                if (data.data.length > 0) {
                    shipId = data.data[0].shipId;
                    $("#shipId").val(data.data[0].shipId);
                    $("#shipName").val(data.data[0].shipName);
                } else {
                    shipId = "";
                    $("#shipId").val("");
                    $("#shipName").val("");
                }

            },
            clear: function () {
                shipId = "";
                $("#shipId").val("");
                $("#shipName").val("");

            }
        })
    }

});


